<template>
  <div class="main">
    <el-form
      ref="formRef"
      :inline="true"
      :model="form"
      class="search-form bg-bg_color w-[99/100] pt-[12px] overflow-auto"
    >
      <el-form-item label="用户" prop="userId">
        <el-select
          ref="userSelectRef"
          v-model="form.userId"
          placeholder="请选择"
          filterable
          remote
          :remote-method="onKeywordInput"
          class="!w-[180px]"
          clearable
          @visible-change="onUserDropdownVisibleChange"
        >
          <el-option
            v-for="item in list"
            :key="item.id"
            :label="item.username"
            :value="item.id"
          />
          <template v-if="userLoading" #footer>
            <div class="text-center text-xs text-gray-500">
              <span>加载中...</span>
            </div>
          </template>
        </el-select>
      </el-form-item>
      <el-form-item label="时间单位" prop="type">
        <el-select
          v-model="form.type"
          class="!w-[80px]"
          placeholder="请选择时间单位"
        >
          <el-option label="日" value="day" />
          <el-option label="周" value="week" />
          <el-option label="月" value="month" />
          <el-option label="年" value="year" />
        </el-select>
      </el-form-item>
      <el-form-item label="日期" prop="time">
        <el-date-picker
          v-model="form.time"
          type="daterange"
          range-separator="-"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          value-format="YYYY-MM-DD"
          class="!w-[220px]"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="success"
          :icon="useRenderIcon('ri:search-line')"
          :loading="loading"
          @click="onSearch"
        >
          搜索
        </el-button>
        <el-button :icon="useRenderIcon(Refresh)" @click="resetForm(formRef)">
          重置
        </el-button>
        <el-button type="success" :loading="exportLoading" @click="exportAll">
          导出所有用户收益
        </el-button>
        <el-button type="success" :loading="exportLoading" @click="exportUser">
          导出指定用户收益
        </el-button>
      </el-form-item>
    </el-form>
    <ExportUsersDialog ref="exportUsersDialogRef" :userList />
    <el-descriptions direction="vertical" :column="3" border>
      <el-descriptions-item label="名称">{{
        tableData?.userInfo?.username ?? "--"
      }}</el-descriptions-item>
      <el-descriptions-item label="利润总额">{{
        tableData?.totalProfit ?? "--"
      }}</el-descriptions-item>
      <el-descriptions-item label="总成本">{{
        tableData?.totalCost ?? "--"
      }}</el-descriptions-item>
      <el-descriptions-item label="总销售">
        {{ tableData?.totalSales ?? "--" }}
      </el-descriptions-item>
      <el-descriptions-item label="总任务">
        {{ tableData?.totalTasks ?? "--" }}
      </el-descriptions-item>
      <el-descriptions-item label="总折扣">
        {{ tableData?.totalDiscount ?? "--" }}
      </el-descriptions-item>
    </el-descriptions>
    <h3 class="pl-4 pt-4 pb-4">服务类型收益统计</h3>
    <el-table :data="tableData?.statsByService" border>
      <el-table-column prop="serviceType" label="服务类型" />
      <el-table-column prop="profit" label="利润" />
      <el-table-column prop="cost" label="成本" />
      <el-table-column prop="sales" label="销售额" />
      <el-table-column prop="tasks" label="任务数" />
    </el-table>
    <h3 class="pl-4 pt-4 pb-4">国家收益统计</h3>
    <el-table :data="tableData?.statsByCountry" border>
      <el-table-column prop="country" label="国家" />
      <el-table-column prop="profit" label="利润" />
      <el-table-column prop="cost" label="成本" />
      <el-table-column prop="sales" label="销售额" />
      <el-table-column prop="tasks" label="任务数" />
    </el-table>
    <h3 class="pl-4 pt-4 pb-4">时间收益统计</h3>
    <el-table :data="tableData?.statsByTime" border>
      <el-table-column prop="period" label="时间" />
      <el-table-column prop="profit" label="利润" />
      <el-table-column prop="cost" label="成本" />
      <el-table-column prop="sales" label="销售额" />
      <el-table-column prop="tasks" label="任务数" />
    </el-table>
    <el-pagination
      v-model:current-page="pagination.currentPage"
      v-model:page-size="pagination.pageSize"
      :page-sizes="[10, 20, 40, 50]"
      background
      layout="total, sizes, prev, pager, next, jumper"
      :total="pagination.total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref, onMounted, nextTick } from "vue";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import Refresh from "@iconify-icons/ep/refresh";
import { getUserProfitStats, exportUserProfit } from "@/api/adminProfitApi";
import dayjs from "dayjs";
import ExportUsersDialog from "./components/ExportUsersDialog.vue";
import {
  userSelectFetcher,
  type UserItem
} from "@/composables/userSelectFetcher";
import { type ElSelect } from "element-plus";
import { useRemotePagedSelect } from "@/composables/useRemotePagedSelect";

// 用户下拉：远程搜索 + 触底加载
const {
  list,
  loading: userLoading,
  onKeywordInput,
  onDropdownScroll,
  load
} = useRemotePagedSelect<UserItem>({
  pageSize: 20,
  autoLoad: false,
  debounceMs: 300,
  fetcher: userSelectFetcher
});

const userSelectRef = ref<InstanceType<typeof ElSelect> | null>(null);
let userDropdownWrapEl: HTMLElement | null = null;

function onUserDropdownVisibleChange(visible: boolean) {
  if (visible) {
    nextTick(() => {
      const popperEl = userSelectRef.value?.popperRef as
        | HTMLElement
        | undefined;
      // 在该选择器自己的 popper 里找 wrap
      userDropdownWrapEl =
        popperEl?.querySelector(".el-select-dropdown__wrap") ?? null;
      userDropdownWrapEl?.addEventListener("scroll", onDropdownScroll, {
        passive: true
      });
    });
  } else {
    userDropdownWrapEl?.removeEventListener("scroll", onDropdownScroll);
    userDropdownWrapEl = null;
  }
}

const formRef = ref();
const loading = ref(false);
const tableData = ref<any>();
const defaultTime = [
  dayjs().startOf("month").format("YYYY-MM-DD"),
  dayjs().endOf("month").format("YYYY-MM-DD")
];
const userList = ref([]);
const form = reactive({
  type: "month",
  time: defaultTime,
  userId: 0
});
const pagination = reactive({
  total: 0,
  pageSize: 10,
  currentPage: 1
});
const exportLoading = ref(false);
const exportAll = async () => {
  try {
    const { time } = form;
    const params = {
      startDate: time[0],
      endDate: time[1]
    };
    exportLoading.value = true;
    await exportUserProfit(params);
  } finally {
    exportLoading.value = false;
  }
};
const exportUsersDialogRef = ref();
const exportUser = () => {
  const { time, type } = form;
  const params = {
    startDate: time[0],
    endDate: time[1],
    timeUnit: type
  };
  exportUsersDialogRef.value?.open(params);
};
const handleSizeChange = (val: number) => {
  pagination.pageSize = val;
  pagination.currentPage = 1;
  onSearch();
};
const handleCurrentChange = (val: number) => {
  pagination.currentPage = val;
  onSearch();
};
async function onSearch() {
  try {
    const { userId, time, type } = form;
    const params = {
      startDate: time[0],
      endDate: time[1],
      type,
      page: pagination.currentPage,
      size: pagination.pageSize
    };
    const { data } = await getUserProfitStats(userId, params);
    tableData.value = data;
    pagination.total = data?.pagination?.total || 0;
    pagination.pageSize = data?.pagination?.size || 10;
    pagination.currentPage = data?.pagination?.page || 1;
  } catch (error) {
    console.error("Error fetching data:", error);
  }
}
const resetForm = formEl => {
  if (!formEl) return;
  formEl.resetFields();
  onSearch();
};
onMounted(async () => {
  await load(1);
  if (list.value.length) {
    form.userId = list.value[0].id;
    onSearch();
  }
});
</script>
<style lang="scss" scoped>
.main {
  padding: 20px;
  background-color: #fff;
}
</style>
